﻿// Copyright 2008 Chris Varley (http://www.contractdriven.net/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Globalization;

namespace ContractDriven.CommonAssertions
{
	/// <summary>
	/// Describes a guarantee that a number is within a particular range.
	/// </summary>
	public class RangeAssertion : IAssertion
    {
        #region Members
        private readonly IComparable _target;
		private readonly IComparable _min;
		private readonly IComparable _max;
        #endregion
        #region Constructor

        /// <summary>
		/// Describes a guarantee that a number is within a particular range.
		/// </summary>
		/// <param name="target">the actual value to be checked.</param>
		/// <param name="min">the minimum value allowed.</param>
		/// <param name="max">the maximum value allowed.</param>
		public RangeAssertion(IComparable target, IComparable min, IComparable max)
		{
			Contract.Require(Assert.IsNotNull(target));
			Contract.Require(Assert.IsNotNull(min));
			Contract.Require(Assert.IsNotNull(max));
			Contract.Require(target.GetType() == min.GetType() && min.GetType() == max.GetType(), "The types of target, min and max must all be the same.");
            Contract.Require(min == max || LessThan(min, max), "Min value specified must be less than max value");
           
			_target = target;
			_min = min;
			_max = max;

        }
        #endregion
        #region IComparable Helpers

        private static bool LessThan(IComparable left, IComparable right)
		{
			return left.CompareTo(right) < 0;
		}

		private static bool GreaterThanOrEqual(IComparable left, IComparable right)
		{
			return left.CompareTo(right) >= 0;
		}

		private static bool LessThanOrEqual(IComparable left, IComparable right)
		{
			return left.CompareTo(right) <= 0;
		}

		#endregion
        #region IAssertion Members

        public string FailureDescription
        {
            get
            {
                return string.Format(CultureInfo.CurrentCulture,
                    _min.GetType() + Resource.RangeAssertion, _min.GetType().FullName, _target, _min, _max);
            }
        }

        public bool Eval()
        {
            return GreaterThanOrEqual(_target, _min) && LessThanOrEqual(_target, _max);
        }

        #endregion
    }
}
